import { Component } from "react";
import { View, Button, Text, ScrollView, Image, Switch } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import homeModel from "@/models/homes";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import { AppState, AppState_Store_Key } from "@/models/appState";
import SDKModel from "@/models/gizwitsSdk";
import loginStateModel from '@/models/loginState';
import deviceListModal, { DeviceList_Store_Key } from '@/models/deviceList';
import deviceDataModal, { DeviceData_Store_Key } from '@/models/deviceData';
import deviceDetailModal from '@/models/deviceDetail';
import { norInject, INorInjectProps } from "@/models";
import { getLoginInfo } from '@/utils/loginStatus';
import ProductConfig, { getItemForPk } from '@/config/product';
import global from '@/utils/global';
import { getProductConfig } from '@/services/applicationConfig';
import Toast from "@/utils/Toast";
import AppService from '@/templates/templateService';

import PageContainer from "@/components/PageContainer";
import "./index.less";
import { Language, Language_Store_Key } from "@/models/language";
import { extractLanguage } from "@/language/tool";

// const plugin = requirePlugin('login-plugin')

interface IProps extends INorInjectProps {
  [Language_Store_Key]: Language
}

const dstyle = GStyleSheet.create({
  text: {
    color: DynamicColors.normalTextColor,
    fontSize: "36rpx",
  },
  box: {
    width: "100rpx",
    height: "100rpx",
    backgroundColor: "#f4a",
  },
});

@norInject(DeviceList_Store_Key, DeviceData_Store_Key, Language_Store_Key)
@observer
class Index extends Component<IProps> {
  initLoading = false;

  async componentWillMount() {
    // 自动初始化一次
    // this.init(false);
  }

  componentDidShow() {
    this.getHomes();
  }

  getHomes = () => {
    // if (this.props.SDK.isInit) {
    //   homesModel.getHomeList();
    // }
  };

  init = async () => {
    if (this.initLoading) return;
    this.initLoading = true;
    Toast.loading('');
    // 更新产品配置
    const data = await getProductConfig();
    if (data.success && data.data && data.data.product_list && data.data.product_list.length > 0) {
      await ProductConfig.updateCacheProducts(data.data && data.data.product_list);
    } else {
      await ProductConfig.init();
    }


    // 登录
    // uid: '069d2517dc7841f9ab34a18e5dc27196', jwtAuthenticationDto: { token: '9eb7af36d23f450e8bd907e7887518b9' }
    await loginStateModel.loginSuccess({ uid: '077dd1dd6e5c496fa67d7dafba10a0d6', jwtAuthenticationDto: { token: '7308937c50d544fea2da458a5feffe73' } });
    const loginInfo = await getLoginInfo();
    if (loginInfo.token) {
      global.token = loginInfo.token;
      // 初始化SDK
      const res = await SDKModel.initWithCurrentLanguage();
      // 一定要获取家庭
      await homeModel.initHomes();
      await deviceListModal.getDeviceList();
      console.log('init', res);
    } else {
      // 未登录，跳转到登录页面
    }
    Toast.hideLoading();
    this.initLoading = false;

  };

  goToDevicePage = (d) => {
    // deviceDetailModal.device = d;
    // AppService.goDeviceInfoPage()
    deviceDataModal?.goToDetailPage(d)
  }

  login = () => {
    // plugin.addTokenListenr((data) => {
    //   console.log("gettoken data", data);
    // })

    // Taro.navigateTo({
    //   url: 'plugin://login-plugin/home',
    // })
  }

  render() {
    const styles = dstyle.style;

    const { languageKey, deviceList, deviceData, language } = this.props;
    console.log("render ", deviceList?.data.length);
    return (
      <PageContainer back={false} title='首页'>
        <Button onClick={this.init}>
          先init
        </Button>
        <Button onClick={()=> {
          const res = require('@/templates/com.gizwits.wx.ai/language/index.json')
          language.loadSubpackgesLanguage(res);
        }}
        >
          load subpackage lang
        </Button>
        <Button onClick={this.login}>
          login
        </Button>
        <View style={{ padding: '10px 20px' }}>
          设备{deviceList?.data.length}台
        </View>
        <ScrollView style={{ height: 400 }} scrollY>
          {
            deviceList?.data.map((device => {
              const pkInfo = getItemForPk(device.productKey) || {};
              let icon = pkInfo.icon;
              let powerAttr = pkInfo.powerAttr || 'power';
              if (pkInfo.offlineIcon && !device.isOnline) {
                icon = pkInfo.offlineIcon
              }

              let showPower = powerAttr && powerAttr !== 'none';
              let power = false;
              if (showPower) {
                const curData = deviceData?.data[device.did] || {};
                power = (curData.data || {})[powerAttr];
              }

              return (
                <View key={device.did} style={{ borderBottom: '1px solid #333', padding: '10px 20px' }} onClick={() => { this.goToDevicePage(device) }}>
                  <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <View>
                      <View style={{ display: 'flex', alignItems: 'center' }}>
                        <Image src={icon} style={{ width: '40px', height: '40px', marginRight: '20px' }} />
                        <Text>{device.name}</Text>
                      </View>
                      <View>
                        <Text>
                          {device.netStatus == 0 ? <Text style={{ color: 'gray' }}>离线</Text> : (
                            device.netStatus == 1 ? '订阅中' : <Text style={{ color: 'green' }}>在线</Text>
                          )}
                        </Text>
                      </View>
                    </View>
                    <View>
                      {showPower && <Switch disabled={device.netStatus !== 2} checked={power} onChange={() => {
                        SDKModel.sendCmd({ device, data: { power: !power } });
                      }}
                      />}
                    </View>
                  </View>
                </View>
              );
            }))
          }
        </ScrollView>

      </PageContainer>
    );
  }
}

export default Index;
